package com.yimingkeji.thymeleaf.service;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Describe:
 * @Auther: zhenlong.yang
 * @Date: 2018/12/14 19:30
 */
@Service
@Slf4j
public class UserService {

    private Map<Integer, User> data;
    /**当前最大的id，新增时使用*/
    private volatile int CURR_ID = 11;

    public UserService(){
        //初始化数据
        data = new ConcurrentHashMap<>(50);
        for(int i=1;i<=10;i++){
            data.put(i, new User(i, "用户---" + i,i%2==0 ? true : false, (20+i), "1800000000" + i));
        }
    }

    public List<User> list(){
        return new ArrayList<>(data.values());
    }

    public User get(int id){
        return data.get(id);
    }

    public User save(User user){
        if(user.getId() != null) {
            data.put(user.getId(), user);
        }else {
            synchronized("1") {
                user.setId(CURR_ID);
                data.put(user.getId(), user);
                CURR_ID++;
            }
        }
        return user;
    }

    public void del(int id){
            data.remove(id);
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class User implements Serializable {
        private Integer id;
        private String name;
        private boolean man;
        private Integer age;
        private String phone;
    }
}
